/**
 * 类名：CoursewareService
 * 创建日期： 2014-11-16 下午3:40:46
 * 
 */
package com.erms.domain;

import java.io.File;

import com.erms.bean.Courseware;
import com.erms.bean.FileInfo;
import com.erms.bean.Teach;
import com.erms.bean.User;
import com.erms.dao.CoursewareDAO;

/**
 * @author hmb
 *         备注：
 * 
 */
public class CoursewareService extends BaseService{
	
	private CoursewareDAO	coursewareDAO;
	private Courseware courseware;

	public Courseware getCourseware() {

		return courseware;
	}

	public void setCourseware(Courseware courseware) {

		this.courseware = courseware;
	}

	public CoursewareDAO getCoursewareDAO() {
	
		return coursewareDAO;
	}

	public void setCoursewareDAO(CoursewareDAO coursewareDAO) {
	
		this.coursewareDAO = coursewareDAO;
	}

	/**
	 * 保存课件
	 * @param userID 上传者id
	 * @param teachID 开课信息id
	 * @param srcFile 文件
	 * @param srcFileName 文件名
	 * @param srcContentType 文件类型
	 * @param newFileName 新文件名
	 * @param description 文件描述
	 * @return 操作结果
	 */
	public boolean save(String userID, String teachID,File srcFile, String srcFileName,
			String srcContentType, String newFileName, String description) {
		logger.debug("保存课件：user="+userID+",teachid="+teachID+"srcfile="+srcFileName);
		boolean result = fileService.save(srcFile, srcFileName, srcContentType, newFileName, description, fileService.TYPE_COURSEWARE_ATTACH_FILE, userID);
		
		try {

			if (result) {				
				User user = new User(userID, null, null);
				fileInfo = fileService.getFileInfo();

				courseware = new Courseware();
				courseware.setFileInfo(fileInfo);
				courseware.setUser(user);
				Teach teach = new Teach();
				teach.setId(teachID);
				courseware.setTeach(teach);
				coursewareDAO.save(courseware);

			}
		} catch (Exception e) {
			// TODO: handle exception
			logger.debug("保存课件失败", e);
			result = false;
		}
		return result;
	}
	/**
	 * 删除课件
	 * @param coursewareID 课件ID
	 * @return 操作结果
	 */
	public boolean delete(Integer coursewareID) {
		logger.debug("删除课件：id="+coursewareID);
		boolean result = true;
		try {
			Courseware courseware = coursewareDAO.findById(coursewareID);
			if (courseware == null) {
				logger.debug("没有找到课件");
				return false;
			}
			fileInfo = courseware.getFileInfo();
			//TODO 注意这里的删除顺序
			coursewareDAO.delete(courseware);
			fileService.delete(fileInfo.getId());
			
			
		} catch (Exception e) {
			// TODO: handle exception
			logger.debug("删除课件失败");
			result = false;
		}
		return result;
	}

	public Courseware find(Integer id) {

		return coursewareDAO.findById(id);
	}
}
